package com.mars.basic.service;

import com.ag.exception.SysException;
import com.mars.basic.allmain.entity.RoleEntity;
import com.mars.basic.allmain.po.QRole;
import com.mars.basic.allmain.vo.RoleVo;
import com.mars.basic.factory.RoleFac;
import com.mars.basic.repository.RoleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@RequiredArgsConstructor(onConstructor =@__(@Autowired))
public class RoleService {

    final RoleRepository userRepository;

    public RoleRepository getRoleRepository(){
        return userRepository;
    }

    public void checkIsExists(RoleVo vo){
        boolean exists = getRoleRepository().exists(QRole.role.name.eq(vo.getName()));
        if (exists){
            throw new SysException(String.format("该[%s]已被注册","账号名称"));
        }
    }
    public boolean checkRoleIsExists(RoleVo vo){
        boolean exists = getRoleRepository().exists(QRole.role.name.eq(vo.getName()));
        return !exists;

    }

    public void addAdmin(RoleVo dto){
        boolean exists = getRoleRepository().exists(QRole.role.name.eq(dto.getName()));
        if (!exists){
            RoleEntity save = getRoleRepository().save(RoleFac.toEntity(dto));
        }
    }
    /**
     * 逻辑需要增强不能删除自己
     * @param id
     * @return
     */
    public void deleteAdmin(Integer id){
        getRoleRepository().deleteById(id);
    }

    public RoleEntity findById(Integer id){
        RoleEntity roleEntity = getRoleRepository().findById(id).orElse(null);
        return roleEntity;
    }
}
